import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'
import Login from '../components/views/Login.vue'
import DingTalkLogin from '../components/views/DingTalkLogin.vue'
import LoginSuccess from '../components/views/LoginSuccess.vue'
import Home from '../components/views/Home.vue'
import JobseekerHome from '../components/views/JobseekerHome.vue'
import RecruiterHome from '../components/views/RecruiterHome.vue'
import IdCardVerification from '../components/views/IdCardVerification.vue'
import Hrview from '../components/views/Hrview.vue'
import JobsView from '../components/views/JobsView.vue'
import CompanyDetailView from '../components/views/CompanyDetailView.vue'
import CompaniesView from '../components/views/CompaniesView.vue'
import ResumeList from '../components/views/ResumeList.vue'
import ResumeView from '../components/views/ResumeView.vue'
import ResumeCreate from '../components/views/ResumeCreate.vue'
import ResumeDetail from '../components/views/ResumeDetail.vue'
import ResumeExport from '../components/views/ResumeExport.vue'
import RecruiterView from '../components/views/RecruiterView.vue'
import Personal from '../../qiye/Personal.vue'
import VipUpgrade from '../components/views/VipUpgrade.vue'

const routes = [
    {
        path: '/',
        name: 'Root',
        redirect: '/hrview'
    },
    {
        path: '/login',
        name: 'Login',
        component: Login,
        meta: {
            title: '登录 - BOSS直聘',
            requiresAuth: true
        }
    },
    {
        path: '/dingtalk-login',
        name: 'DingTalkLogin',
        component: DingTalkLogin,
        meta: {
            title: '钉钉扫码登录 - BOSS直聘',
            requiresAuth: false
        }
    },
    {
        path: '/login-success',
        name: 'LoginSuccess',
        component: LoginSuccess,
        meta: {
            title: '登录成功 - BOSS直聘',
            requiresAuth: false
        }
    },
    {
        path: '/home',
        name: 'Home',
        component: Home,
        meta: {
            title: '首页 - BOSS直聘',
            requiresAuth: false
        }
    },
    {
        path: '/jobseeker',
        name: 'JobseekerHome',
        component: JobseekerHome,
        meta: {
            title: '求职者首页 - BOSS直聘',
            requiresAuth: true
        }
    },
    {
        path: '/recruiter',
        name: 'RecruiterHome',
        component: RecruiterHome,
        meta: {
            title: '招聘者首页 - BOSS直聘',
            requiresAuth: true
        }
    },
    {
        path: '/recruiter-view',
        name: 'RecruiterView',
        component: RecruiterView,
        meta: {
            title: '招聘者工作台 - BOSS直聘',
            requiresAuth: true
        }
    },
    {
        path: '/personal',
        name: 'Personal',
        component: Personal,
        meta: {
            title: '创建BOSS名片 - BOSS直聘',
            requiresAuth: true
        }
    },
    {
        path: '/idcard-verification',
        name: 'IdCardVerification',
        component: IdCardVerification,
        meta: {
            title: '实名认证 - BOSS直聘',
            requiresAuth: true
        }
    },
    {
        path: '/hrview',
        name: 'Hrview',
        component: Hrview,
        meta: {
            title: '首页 - BOSS直聘',
            requiresAuth: false
        }
    },
    {
        path: '/jobs',
        name: 'JobsView',
        component: JobsView,
        meta: {
            title: '职位详情 - BOSS直聘',
            requiresAuth: true
        }
    },
    {
        path: '/company/:id',
        name: 'CompanyDetail',
        component: CompanyDetailView,
        meta: {
            title: '公司详情 - BOSS直聘',
            requiresAuth: true
        }
    },
    {
        path: '/companies',
        name: 'Companies',
        component: CompaniesView,
        meta: {
            title: '公司列表 - BOSS直聘',
            requiresAuth: true
        }
    },
    {
        path: '/resume',
        name: 'ResumeList',
        component: ResumeList,
        meta: {
            title: '我的简历 - BOSS直聘',
            requiresAuth: true
        }
    },
    {
        path: '/resume/create',
        name: 'ResumeCreate',
        component: ResumeCreate,
        meta: {
            title: '创建简历 - BOSS直聘',
            requiresAuth: true
        }
    },
    {
        path: '/resume/view',
        name: 'ResumeView',
        component: ResumeView,
        meta: {
            title: '简历预览 - BOSS直聘',
            requiresAuth: true
        }
    },
    {
        path: '/resume/:id',
        name: 'ResumeDetail',
        component: ResumeDetail,
        meta: {
            title: '简历详情 - BOSS直聘',
            requiresAuth: true
        }
    },
    {
        path: '/resume/export',
        name: 'ResumeExport',
        component: ResumeExport,
        meta: {
            title: '简历导出 - BOSS直聘',
            requiresAuth: true
        }
    },
    // 企业相关路由
    {
        path: '/enterprise',
        children: [
            {
                path: 'login',
                name: 'enterpriseLogin',
                component: () => import('../../qiye/EnLogin.vue'),
                meta: {
                    title: '企业登录 - BOSS直聘',
                    requiresAuth: false
                }
            },
            {
                path: 'personal',
                name: 'enterprisePersonal',
                component: () => import('../../qiye/Personal.vue'),
                meta: {
                    title: '创建BOSS名片 - BOSS直聘',
                    requiresAuth: true
                }
            },
            {
                path: 'company',
                name: 'enterpriseCompany',
                component: () => import('../../qiye/Company.vue'),
                meta: {
                    title: '企业信息 - BOSS直聘',
                    requiresAuth: true
                }
            },
            {
                path: 'main',
                name: 'enterpriseMain',
                component: () => import('../../qiye/Main.vue'),
                meta: {
                    title: '企业主页 - BOSS直聘',
                    requiresAuth: true
                }
            },
            {
                path: 'company-info',
                name: 'enterpriseCompanyInfo',
                component: () => import('../../qiye/CompanyInfo.vue'),
                meta: {
                    title: '企业信息 - BOSS直聘',
                    requiresAuth: true
                }
            }
        ]
    },
    {
        path: '/map',
        name: 'Map',
        component: ()=>import('../components/views/Map.vue'),
        meta: {
            title: '地图 - BOSS直聘',
            requiresAuth: false
        }
    },
    {
        path: '/vip-upgrade',
        name: 'VipUpgrade',
        component: VipUpgrade,
        meta: {
            title: 'VIP升级 - BOSS直聘',
            requiresAuth: false
        }
    },
    {
        path: '/vip-pay',
        name: 'VipPay',
        component: () => import('../components/views/WeChatNativePay.vue'),
        meta: {
            title: 'VIP支付 - BOSS直聘',
            requiresAuth: true
        }
    }
]

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
    // 设置页面标题
    document.title = to.meta.title || 'BOSS直聘'

    const userStore = useUserStore()
    const isLoggedIn = userStore.isLoggedIn

    console.log('🔍 路由守卫:', {
        to: to.path,
        from: from.path,
        isLoggedIn: isLoggedIn,
        userType: userStore.user?.user_type
    })

    // 检查是否是钉钉登录回调（URL中携带token）
    const hasTokenInUrl = to.query.token

    // 如果需要认证
    if (to.meta.requiresAuth) {
        // 如果URL中有token（钉钉回调），允许通过
        if (isLoggedIn || hasTokenInUrl) {
            next()
        } else {
            console.log('🚫 未登录，重定向到登录页')
            next('/login')
        }
    } else {
        // 如果已登录用户访问登录页，根据用户角色重定向
        if (to.path === '/login' && isLoggedIn) {
            const userType = userStore.user?.user_type
            const targetRoute = userType === 'recruiter' ? '/recruiter' : '/home'
            console.log('✅ 已登录访问登录页，根据角色重定向到:', targetRoute)
            next(targetRoute)
        } else {
            next()
        }
    }
})

export default router